'use strict'

const http = require('http')

let html=`
<!DOCTYPE html>
<html>
    <head><title>first HTTP</title></head>
    <body>
        你好。
    </body>
</html>
`

let routerTable = {
    '/':async(req,res)=>{
        res.setHeader('content-type','text/html;charset=utf-8');//构造消息头
            // // text/plain:不解析HTML代码
            // // text/HTML：解析HTML代码
        res.end(html)
    },

    '/test':async(req,res)=>{
        let status = parseInt(Math.random() * 200) + 199
        res.statusCode = status
        res.end('test end')
    },

    '/data':async(req,res)=>{             //接收数据
        let bufferList = []
        let bufferLength = 0

        req.on('data',chunk=>{
            bufferLength += chunk.length
            bufferList.push(chunk)        //将数据添加进bufferList中
        })

        let bodyData = null;
        req.on('end',()=>{
            if(bufferList.length > 0){
                bodyData = Buffer.concat(bufferList,bufferLength)  //将数组中的数拼接成一个Buffer，返回给badyData
                bufferList = []   //释放bufferList
            }

            if(bodyData){
                res.end(bodyData)
            }else{
                res.end()
            }
        })
    }
}

http.createServer((req,res)=>{
    if(!routerTable[req.url]){
        res.statusCode = 404
        res.end('page not found')
        return
    }
    routerTable[req.url](req,res)
}).listen(3456)